package com.example.test622.ui.cinema

import androidx.lifecycle.viewModelScope
import com.example.common.mvi.BaseViewModel
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class CinemaViewModel : BaseViewModel<CinemaIntent, CinemaState>() {
	init {
		viewModelScope.launch {
			intent.consumeAsFlow().collect {
				when (it) {
					is CinemaIntent.LoadMutil -> {
						loadMutilType()
					}
					
					is CinemaIntent.LoadMutilBypid -> {
						loadMutilTypeBypid(it.pid)
					}
					
					is CinemaIntent.LoadMutilVideo -> {
						loadMutilVideo(it.page, it.size, it.type)
					}
				}
			}
		}
	}
	
	private suspend fun loadMutilVideo(page: Int, size: Int, type: Int) {
		val s = try {
			val res = service.getMutilVideo(page, size, type)
			if (res.code == 0) {
				CinemaState.getMutilVideo(res)
			} else {
				CinemaState.failue(res.msg)
			}
		} catch (e: Exception) {
			CinemaState.failue(e.message ?: "")
		}
		state.postValue(s)
	}
	
	private suspend fun loadMutilTypeBypid(pid: Int) {
		val s = try {
			val res = service.getMutilTypeByPid(pid)
			if (res.code == 0) {
				CinemaState.getMutiltypeByPid(res)
			} else {
				CinemaState.failue(res.msg)
			}
		} catch (e: Exception) {
			CinemaState.failue(e.message ?: "")
		}
		state.postValue(s)
	}
	
	private suspend fun loadMutilType() {
		val s = try {
			val res = service.getMutilType()
			if (res.code == 0) {
				CinemaState.getMutiltype(res)
			} else {
				CinemaState.failue(res.msg)
			}
		} catch (e: Exception) {
			CinemaState.failue(e.message ?: "")
		}
		state.postValue(s)
	}
}